using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseRead.API.Applications.Commands.Drugstores;
using ContentmanagementBaseRead.API.Dtos;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace ContentmanagementBaseRead.API.Applications.Commandhandlters.Drugstores
{
    /// <summary>
    /// 获取药店列表信息命令处理
    /// </summary>
    public class GetDrugstoreListCommandHandler : IRequestHandler<GetDrugstoreListCommand, ApiPaging<List<DrugstoreListDto>>>
    {
        /// <summary>
        /// 药店仓储
        /// </summary>
        private readonly IBaseRepository<PharmacyManagementModel> _drugstoreRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<GetDrugstoreListCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="drugstoreRepository">药店仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetDrugstoreListCommandHandler(
            IBaseRepository<PharmacyManagementModel> drugstoreRepository,
            IMapper mapper,
            ILogger<GetDrugstoreListCommandHandler> logger)
        {
            _drugstoreRepository = drugstoreRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取药店列表信息命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiPaging<List<DrugstoreListDto>>> Handle(GetDrugstoreListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取药店列表信息，参数：PageIndex={PageIndex}, PageSize={PageSize}", 
                    request.PageIndex, request.PageSize);

                // 获取所有药店数据（排除已删除的）
                var query = _drugstoreRepository.GetAll().AsNoTracking().Where(x => !x.IsDeleted);

                // 应用搜索条件
                if (!string.IsNullOrEmpty(request.PharmacyName))
                {
                    query = query.Where(x => x.PharmacyName.Contains(request.PharmacyName));
                    _logger.LogDebug("应用药店名称搜索条件：{PharmacyName}", request.PharmacyName);
                }

                if (!string.IsNullOrEmpty(request.PharmacyAddress))
                {
                    query = query.Where(x => x.PharmacyAddress.Contains(request.PharmacyAddress) || x.PharmacyAreas.Contains(request.PharmacyAddress));
                    _logger.LogDebug("应用所在地区搜索条件：{PharmacyAddress}", request.PharmacyAddress);
                }


                // 按创建时间倒序排列
                query = query.OrderByDescending(x => x.CreatedTime);

                // 获取总数量
                var totalCount = await query.CountAsync(cancellationToken);
                
                // 计算分页信息
                var pageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);
                var skip = (request.PageIndex - 1) * request.PageSize;

                // 获取分页数据
                var pagedData = await query.Skip(skip).Take(request.PageSize).ToListAsync(cancellationToken);

                // 映射到DTO
                var drugstoreListDtos = _mapper.Map<List<DrugstoreListDto>>(pagedData);

                _logger.LogInformation("药店列表信息获取成功，共获取到 {Count} 个药店，总数量：{TotalCount}", 
                    drugstoreListDtos.Count, totalCount);

                return new ApiPaging<List<DrugstoreListDto>>
                {
                    code = ResultEnumCode.Ok,
                    message = "药店列表信息获取成功",
                    data = drugstoreListDtos,
                    TotalCount = totalCount,
                    PageCount = pageCount
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取药店列表信息过程中发生异常");
                return new ApiPaging<List<DrugstoreListDto>>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取药店列表信息失败：{ex.Message}",
                    data = new List<DrugstoreListDto>(),
                    TotalCount = 0,
                    PageCount = 0
                };
            }
        }
    }
}